package org.edu.dao.impl;

import java.util.List;

import org.edu.dao.UserDao;
import org.edu.model.User;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {

	@Autowired
	private SessionFactory sessionFactory;
	public UserDaoImpl() {

	}

	@Override
	public void save(User user) throws Exception {
		sessionFactory.getCurrentSession().save(user);
	}

	@Override
	public void update(User user) throws Exception {
		sessionFactory.getCurrentSession().update(user);
	}

	@Override
	public void delete(User user) throws Exception {
		this.sessionFactory.getCurrentSession().delete(user);
	}

	@Override
	public User getUser(User user) throws Exception {
		String sql = "SELECT u FROM User u WHERE user_number=:user_number and password=:password";
		Query query = sessionFactory.getCurrentSession().createQuery(sql);
		query.setString("user_number", user.getUser_number());
		query.setString("password", user.getPassword());
		return (User) query.uniqueResult();
	}

	@Override
	public List<User> users() {
		return sessionFactory.getCurrentSession().createQuery("from User").list();
	}

	@Override
	public User findById(Long user_id) throws Exception {
		return (User) sessionFactory.getCurrentSession().load(User.class, user_id); 
	}

}
